package org.kamionowski.supreme.controllers.search;

import org.kamionowski.supreme.controllers.base.AbstractJsonController;
import org.kamionowski.supreme.services.search.SearchFileDscService;
import org.kamionowski.supreme.services.search.tools.FileDscBean;
import org.kamionowski.supreme.services.search.tools.FileType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;
import org.apache.commons.lang.Validate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.kamionowski.supreme.services.search.QueryToken;
import org.kamionowski.supreme.services.search.TokenService;

/**
 * Created by IntelliJ IDEA.
 * User: Marcin Kamionowski
 * Date: 04.04.11
 * Time: 23:51
 */
@RequestMapping("/search")
@Controller
public class SearchController extends AbstractJsonController {

    @Autowired
    private SearchFileDscService searchFileDscService;
    @Autowired
    private TokenService tokenService;
    private Log log = LogFactory.getLog(SearchController.class);

    @RequestMapping(value = "/file", method = RequestMethod.POST)
    public ModelAndView searchFile(
            @RequestParam String expression,
            @RequestParam(required = false, defaultValue = "true") Boolean caseMatch,
            @RequestParam(required = false) Date modificationFrom,
            @RequestParam(required = false) Date modificationTo,
            @RequestParam(required = false) FileType[] type
    ){
        FileDscBean fileDscBean = new FileDscBean();
        fileDscBean.setExpression(expression);
        fileDscBean.setCaseMatch(caseMatch);
        fileDscBean.setModificationFrom(modificationFrom);
        fileDscBean.setModificationTo(modificationTo);
        fileDscBean.setType(type);
        objects.put("files", searchFileDscService.searchFiles(fileDscBean));
        return createJson();
    }

    @RequestMapping(value = "/autocomplete", method = RequestMethod.POST)
    public ModelAndView autocomplete(@RequestParam String query, @RequestParam Integer limit){
        Validate.notNull(query);
        Validate.notNull(limit);
        if(limit > 100){
            log.warn("Requested " + limit + " tokens - change to maximum value.");
            limit = 100;
        }
        List<QueryToken> tokens = tokenService.searchForTokensMatchingQueryString(query, limit);
        objects.put("tokens", tokens);
        return createJson();
    }
}
